package ws.very.web.tpl.nutz

import org.nutz.mvc.ViewMaker
import org.nutz.ioc.Ioc
import org.nutz.lang.Streams
import javax.servlet.http.HttpServletRequest
import ws.very.web.tpl.HttpExpand
import javax.servlet.http.HttpServletResponse
import ws.very.web.tpl.Html
import org.nutz.mvc.View
import scala.collection.convert.WrapAsScala
import scala.collection.convert.WrapAsJava
import org.nutz.mvc.Mvcs
import org.nutz.json.JsonFormat
import org.nutz.json.Json
import ws.very.util.lang.Scala2JavaColl

class VeryViewMarker extends ViewMaker {
  override def make(ioc: Ioc, typ: String, value: String) =
    typ match {
      case "ws" | "whtml" => VeryHtmlView //ws为历史版本兼容
      case "wjson" => if (value == null) new VeryJsonView(JsonFormat.compact()) else new VeryJsonView(Json.fromJson(classOf[JsonFormat], value))
      case _ => null
    }

}
object VeryHtmlView extends View with HttpExpand {
  override def render(req: HttpServletRequest, resp: HttpServletResponse, obj: Object) = {
    val html = obj.asInstanceOf[Html]
    resp.setContentType(html.contentType)
    Streams.writeAndClose(resp.getWriter, req.pageFixs.foldLeft(html.buffer) { (str, fn) =>
      fn(str)
    })

  }
}
class VeryJsonView(format: JsonFormat) extends View with WrapAsJava {

  var data: Any = null
  override def render(req: HttpServletRequest, resp: HttpServletResponse, obj: Object) = {
    Mvcs.write(resp, (if (obj == null) data else obj), format)
  }

}